package picounit.ruby;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.bsf.util.IOUtils;

import picounit.ruby.exception.FileNotFound;
import picounit.ruby.exception.FileNotReadable;

public class FileUtil {
    public String fileContents(String filename) {
        try {
            FileReader fileReader = new FileReader(findFile(filename));

            return IOUtils.getStringFromReader(fileReader);
        }
        catch (FileNotFoundException fileNotFoundException) {
            throw new FileNotFound(fileNotFoundException);
        }
        catch (IOException ioException) {
            throw new FileNotReadable(ioException);
        }
    }

    private String[] classpath() {
        return System.getProperty("java.class.path").split(":");
    }

    private File findFile(String filename) {
        for (String pathElement : classpath()) {
            File file = new File(pathElement + File.separatorChar + filename);

            if (file.exists()) {
                return file;
            }
            else {
                System.out.println("Not: " +file);
            }
        }

        System.out.println(new File(getClass().getResource("/").getFile()));

        throw new FileNotFound(filename);
    }
}